﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeBuilder.DTO
{
    public class CreateDtoBase
    {
        private string tableName;
        private string fileDir;
        private DataTable dataTable;
        public CreateDtoBase(string tableName, string fileDir, DataTable dataTable)
        {
            this.tableName = tableName;
            this.fileDir = fileDir;
            this.dataTable = dataTable;
        }

        public void Run()
        {
            var dtoName = "DtoBase";
            IList<string> contents = new List<string>();
            contents.Add($"using CommunityToolkit.Mvvm.ComponentModel;");
            contents.Add($"");
            contents.Add($"namespace Hualong.TestWorldPro.Dto");
            contents.Add("{");
            contents.Add($"    public partial class DtoBase : ObservableObject");
            contents.Add("    {");
            foreach (DataRow fieldItem in dataTable.Rows)
            {
                if (fieldItem[0].ToString() == "id" || fieldItem[0].ToString() == "sort"
                    || fieldItem[0].ToString() == "is_deleted" || fieldItem[0].ToString() == "create_user"
                    || fieldItem[0].ToString() == "create_time" || fieldItem[0].ToString() == "update_user"
                    || fieldItem[0].ToString() == "update_time")
                {
                    var notNull = "?";
                    if (fieldItem[2].ToString() == "NO")
                    {
                        notNull = "";
                    }
                    contents.Add($"        [ObservableProperty]");
                    contents.Add($"        private {DataTypeMap.Get(fieldItem[1].ToString())}{notNull} {Helper.GetCamelCase(fieldItem[0].ToString())};");
                }
            }
            contents.Add("    }");
            contents.Add("}");
            string filePath = Path.Combine(fileDir, dtoName);

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(filePath, $"{dtoName}.cs");
            if (File.Exists(filePath))
            { File.Delete(filePath); }
            File.WriteAllLines(filePath, contents, Encoding.UTF8);


            Console.WriteLine($"创建:{filePath} 完成！");
        }
    }
}
